import React, { useState } from 'react'
import style from './style.module.scss'
import { CodeTextView } from './CodeTextView'

interface IVerifyCodeProps {
    onChange?: (value: string) => void
}

export function VerifyCodeTextView(props: IVerifyCodeProps) {
    const [code, setCode] = useState<Array<string>>(['', '', '', '', '', ''])
    const [selectedIndex, setSelectedIndex] = useState(0)

    const onChange = (index: number, value: string) => {
        if (!isNaN(parseInt(value))) {
            if (value !== '-1') {
                code[index] = value
                setCode([...code])
                setSelectedIndex(selectedIndex + 1 > 6 ? 5 : selectedIndex + 1)
                if (props.onChange) props.onChange(code.join('').toString())
            } else {
                code[index] = ''
                setCode([...code])
                if (selectedIndex - 1 >= 0) setSelectedIndex(selectedIndex - 1)
            }
        }
    }

    return (
        <div className={style.wrapper}>
            <CodeTextView index={0} value={code} selectedIndex={selectedIndex} onInput={onChange} />
            <CodeTextView index={1} value={code} selectedIndex={selectedIndex} onInput={onChange} />
            <CodeTextView index={2} value={code} selectedIndex={selectedIndex} onInput={onChange} />
            <CodeTextView index={3} value={code} selectedIndex={selectedIndex} onInput={onChange} />
            <CodeTextView index={4} value={code} selectedIndex={selectedIndex} onInput={onChange} />
            <CodeTextView index={5} value={code} selectedIndex={selectedIndex} onInput={onChange} />
        </div>
    )
}
